package kr.co.project1.base.taglib;

import java.io.Writer;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class Paginator extends SimpleTagSupport {
	
	private String uri;
	private int currPage;
	private int totalPages;
	private int maxLinks = 10;

	private Writer getWriter() {
		JspWriter out = getJspContext().getOut();
		return out;
	}

	@Override
	public void doTag() throws JspException {
		Writer out = getWriter();

		boolean lastPage = currPage == totalPages;
		int pgStart = Math.max(currPage - maxLinks / 2, 1);
		int pgEnd = pgStart + maxLinks;
		if (pgEnd > totalPages + 1) {
			int diff = pgEnd - totalPages;
			pgStart -= diff - 1;
			if (pgStart < 1)
				pgStart = 1;
			pgEnd = totalPages + 1;
		}
		
		String className = null;

		try {
			out.write("<div class=\"pagination\"><ul>");

			if (currPage == 1) className="disabled";
			out.write(constructLink(currPage - 1, "Prev", className));

			for (int i = pgStart; i < pgEnd; i++) {
				if (i == currPage) 
					out.write("<li class=\"active\"><span>" + currPage + "</span></li>");
				else out.write(constructLink(i));
			}

			if (lastPage) className = "disabled";
			else className = null;
			out.write(constructLink(currPage + 1, "Next", className));

			out.write("</ul></div>");

		} catch (java.io.IOException ex) {
			throw new JspException("Error in Paginator tag", ex);
		}
	}

	private String constructLink(int page) {
		return constructLink(page, String.valueOf(page), null);
	}

	private String constructLink(int page, String text, String className) {
		StringBuilder element = new StringBuilder("<li");
		if (className != null) {
			element.append(" class=\"");
			element.append(className);
			element.append("\"");
		}
		
		if("disabled".equals(className)){
			element.append(">").append("<span>").append(text).append("</span></li>");
		}else{
			element.append(">").append("<a href=\"").append(uri);
			if(uri.indexOf("?") == -1){
				element.append("?page=");
			}else{
				element.append("&page=");
			}
			element.append(page).append("\">").append(text).append("</a></li>");
		}
		
		return element.toString();
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public void setCurrPage(int currPage) {
		this.currPage = currPage;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public void setMaxLinks(int maxLinks) {
		this.maxLinks = maxLinks;
	}
}
